import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		loginState: uni.getStorageSync('loginState') === 'ok' ? true : false,
		userInfo: uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : {
			name: '',
			avater: '/static/images/nopic.png',
			liked: 0,
			commented: 0
		}
	},
	getters: {

	},
	mutations: {
		userLogin(state, payload) {
			state.loginState = true,
			state.userInfo = payload
			// 保证数据持久化
			uni.setStorageSync('loginState', 'ok')
			uni.setStorageSync('userInfo', JSON.stringify(payload))
		},
		userLogout(state) {
			state.loginState = false,
			state.userInfo = {
				name: '',
				avater: '/static/images/nopic.png',
				liked: 0,
				commented: 0
			}
			// 退出后,清除所有保存在本地的数据
			uni.clearStorageSync('loginState')
			uni.clearStorageSync('userInfo')
			uni.clearStorageSync('token')
		}
	},
	actions: {
		userLoginActions(context, payload) {
			context.commit('userLogin', payload)
		},
		userLogoutAction(context) {
			context.commit('userLogout')
		}
	},

})

export default store
